<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch && !hideUI" label-width="68px">
      <el-form-item label="合同编号" prop="contractNo">
        <el-input
          v-model="queryParams.contractNo"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同类型" prop="contractType">
        <el-select v-model="queryParams.contractType" placeholder="请选择合同类型" clearable>
          <el-option
            v-for="dict in dict.type.contract_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同状态" prop="contractStatus">
        <el-select v-model="queryParams.contractStatus" placeholder="请选择合同状态" clearable>
          <el-option
            v-for="dict in dict.type.contract_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="!hideUI">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['lock:contract:add']"
        >新增</el-button>
      </el-col> -->
     <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lock:contract:edit']"
        >修改</el-button>
      </el-col> -->
    <!--  <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lock:contract:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['lock:contract:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="合同ID" align="center" prop="id" /> -->
      <el-table-column label="合同编号" align="center" prop="contractNo" />
      <el-table-column label="人员ID" align="center" prop="tenantId" />
      <el-table-column label="合同类型" align="center" prop="contractType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.contract_type" :value="scope.row.contractType"/>
        </template>
      </el-table-column>
      <el-table-column label="合同状态" align="center" prop="contractStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.contract_status" :value="scope.row.contractStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="签约日期" align="center" prop="signDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同周期" align="center" width="250">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }} 至 {{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="距离到期" align="center" width="120">
        <template slot-scope="scope">
          <span :class="getRemainingDaysClass(scope.row.endDate)">
            {{ getRemainingDaysText(scope.row.endDate) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="月租金(元)" align="center" prop="rentAmount" />
      <el-table-column label="押金(元)" align="center" prop="depositAmount" />
      <el-table-column label="支付方式" align="center" prop="paymentMethod" />
      <el-table-column label="每月缴费日" align="center" prop="paymentDay" />
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="合同附件" align="center" width="100">
        <template slot-scope="scope">
          <el-button
            v-if="hasAttachments(scope.row.attachmentUrls)"
            size="mini"
            type="primary"
            icon="el-icon-download"
            @click="handleDownloadAttachments(scope.row)"
          >下载</el-button>
          <span v-else>无</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="是否删除" align="center" prop="isDeleted">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.del_flag" :value="scope.row.isDeleted"/>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['lock:contract:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['lock:contract:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-empty v-if="contractList.length === 0 && !loading" description="暂无合同信息"></el-empty>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学校合同主对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row v-if="form.id">
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractNo">
              <el-input v-model="form.contractNo" placeholder="请输入合同编号" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人员ID" prop="tenantId">
              <el-input v-model="form.tenantId" placeholder="请输入人员ID" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同类型" prop="contractType">
              <el-radio-group v-model="form.contractType">
                <el-radio
                  v-for="dict in dict.type.contract_type"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同状态" prop="contractStatus">
              <el-select v-model="form.contractStatus" placeholder="请选择合同状态">
                <el-option
                  v-for="dict in dict.type.contract_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="签约日期" prop="signDate">
              <el-date-picker clearable
                v-model="form.signDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择签约日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同开始日期" prop="startDate">
              <el-date-picker clearable
                v-model="form.startDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择合同开始日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同结束日期" prop="endDate">
              <el-date-picker clearable
                v-model="form.endDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择合同结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="月租金(元)" prop="rentAmount">
              <el-input v-model="form.rentAmount" placeholder="请输入月租金(元)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="押金(元)" prop="depositAmount">
              <el-input v-model="form.depositAmount" placeholder="请输入押金(元)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="每月缴费日" prop="paymentDay">
              <el-input v-model="form.paymentDay" placeholder="请输入每月缴费日" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="form.paymentMethod" placeholder="请选择支付方式">
                <el-option label="月付" value="1"></el-option>
                <el-option label="季付" value="2"></el-option>
                <el-option label="半年付" value="3"></el-option>
                <el-option label="年付" value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同附件" prop="attachmentUrls">
              <file-upload v-model="form.attachmentUrls"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 附件下载对话框 -->
    <el-dialog
      :title="`下载附件`"
      :visible.sync="attachmentDialogVisible"
      width="800px"
      append-to-body
    >
      <div class="attachment-container">
        <el-row v-for="(attachment, index) in currentAttachments" :key="index">
          <el-col :span="12">
            <el-button
              type="primary"
              @click="handleDownloadAttachment(attachment.url)"
              :loading="downloading"
              icon="el-icon-download"
            >
              {{ attachment.name }}
            </el-button>
          </el-col>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="attachmentDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listContract, getContract, delContract, addContract, updateContract } from "@/api/lock/contract";

export default {
  name: "Contract",
  dicts: ['contract_type', 'contract_status'],
  props: {
    // 房间ID
    homeId: {
      type: [String, Number],
      default: null
    },
    // 控制搜索和工具栏的显示
    hideUI: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学校合同主表格数据
      contractList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractNo: null,
        contractType: null,
        contractStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        contractType: [
          { required: true, message: "合同类型不能为空", trigger: "change" }
        ],
        contractStatus: [
          { required: true, message: "合同状态不能为空", trigger: "change" }
        ],
        signDate: [
          { required: true, message: "签约日期不能为空", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "合同开始日期不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "合同结束日期不能为空", trigger: "blur" }
        ],
        rentAmount: [
          { required: true, message: "月租金(元)不能为空", trigger: "blur" }
        ],
        depositAmount: [
          { required: true, message: "押金(元)不能为空", trigger: "blur" }
        ],
        paymentMethod: [
          { required: true, message: "支付方式不能为空", trigger: "change" }
        ],
        paymentDay: [
          { required: true, message: "每月缴费日不能为空", trigger: "blur" }
        ],
      },
      // 附件下载对话框
      attachmentDialogVisible: false,
      currentAttachments: [],
      // 附件下载中标志
      downloading: false
    };
  },
  created() {
    // 如果有homeId参数，则添加到查询条件中
    if (this.homeId) {
      this.queryParams.homeId = this.homeId;
    }
    this.getList();
  },
  methods: {
    /** 查询学校合同主列表 */
    getList() {
      this.loading = true;
      // 确保每次查询都用上最新的homeId
      if (this.homeId) {
        this.queryParams.homeId = this.homeId;
      }
      listContract(this.queryParams).then(response => {
        this.contractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        contractNo: null,
        tenantId: null,
        contractType: null,
        contractStatus: null,
        signDate: null,
        startDate: null,
        endDate: null,
        rentAmount: null,
        depositAmount: null,
        paymentMethod: null,
        paymentDay: null,
        remark: null,
        attachmentUrls: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDeleted: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学校合同";
      // 新增时不需要设置合同编号和人员ID，由后端生成
      this.form.contractNo = null;
      this.form.tenantId = null;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getContract(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改学校合同";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateContract(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContract(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除学校合同主编号为"' + ids + '"的数据项？').then(function() {
        return delContract(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('lock/contract/export', {
        ...this.queryParams
      }, `contract_${new Date().getTime()}.xlsx`)
    },
    /** 检查是否有附件 */
    hasAttachments(attachmentUrls) {
      if (!attachmentUrls) return false;

      // 如果是字符串，且不为空
      if (typeof attachmentUrls === 'string') {
        if (attachmentUrls.trim() === '') return false;
        if (attachmentUrls.startsWith('[')) {
          try {
            const parsedUrls = JSON.parse(attachmentUrls);
            return Array.isArray(parsedUrls) && parsedUrls.length > 0;
          } catch (e) {
            return attachmentUrls.trim() !== '';
          }
        }
        return attachmentUrls.trim() !== '';
      }

      // 如果是数组
      if (Array.isArray(attachmentUrls)) {
        return attachmentUrls.length > 0;
      }

      return false;
    },
    /** 处理下载附件 */
    handleDownloadAttachments(row) {
      if (!row.attachmentUrls) return;

      let attachmentUrls = [];

      try {
        // 尝试解析附件URLs（可能是JSON字符串或逗号分隔的URL列表）
        if (typeof row.attachmentUrls === 'string') {
          if (row.attachmentUrls.startsWith('[')) {
            // 如果是JSON格式
            attachmentUrls = JSON.parse(row.attachmentUrls);
          } else {
            // 如果是逗号分隔的字符串
            attachmentUrls = row.attachmentUrls.split(',').filter(url => url.trim() !== '');
          }
        } else if (Array.isArray(row.attachmentUrls)) {
          // 如果已经是数组
          attachmentUrls = row.attachmentUrls;
        }

        // 简单处理：直接下载第一个附件
        if (attachmentUrls.length > 0) {
          const url = this.formatUrl(attachmentUrls[0]);
          // 如果只有一个附件，直接下载
          if (attachmentUrls.length === 1) {
            window.open(url);
          } else {
            // 如果有多个附件，显示下载对话框
            this.currentAttachments = attachmentUrls.map((url, index) => {
              // 从URL提取文件名
              const parts = url.split('/');
              const fileName = parts[parts.length - 1] || `附件${index + 1}`;

              return {
                url: this.formatUrl(url),
                name: fileName
              };
            });
            this.attachmentDialogVisible = true;
          }
        }
      } catch (error) {
        console.error('解析附件URLs出错:', error);
        this.$message.error('下载附件失败');
      }
    },
    /** 格式化URL */
    formatUrl(url) {
      if (!url) return '';

      // 如果已经是完整的URL，则直接返回
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }

      // 如果是以/开头的相对路径，添加基础API地址
      if (url.startsWith('/')) {
        return process.env.VUE_APP_BASE_API + url;
      }

      // 其他情况，确保有正确的路径分隔符，然后添加基础API地址
      return process.env.VUE_APP_BASE_API + (url.startsWith('/') ? '' : '/') + url;
    },
    /** 下载单个附件 */
    handleDownloadAttachment(url) {
      if (!url) return;
      window.open(url);
    },
    /** 计算合同距离到期天数 */
    getRemainingDays(endDateStr) {
      if (!endDateStr) return null;

      try {
        // 解析结束日期
        const endDate = new Date(endDateStr);
        const today = new Date();

        // 设置时间为一天的结束
        endDate.setHours(23, 59, 59, 999);

        // 计算相差的毫秒数
        const diffTime = endDate.getTime() - today.getTime();
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

        return diffDays;
      } catch (error) {
        console.error('计算合同到期天数出错:', error);
        return null;
      }
    },
    /** 获取合同到期天数显示文本 */
    getRemainingDaysText(endDateStr) {
      const days = this.getRemainingDays(endDateStr);

      if (days === null) return '-';

      if (days < 0) {
        return `已过期 ${Math.abs(days)} 天`;
      } else if (days === 0) {
        return '今日到期';
      } else {
        return `剩余 ${days} 天`;
      }
    },
    /** 获取合同到期天数显示样式 */
    getRemainingDaysClass(endDateStr) {
      const days = this.getRemainingDays(endDateStr);

      if (days === null) return '';

      if (days < 0) {
        return 'text-danger'; // 已过期
      } else if (days <= 30) {
        return 'text-warning'; // 即将到期（30天内）
      } else {
        return 'text-success'; // 还有较长时间
      }
    }
  },
  computed: {
    // 是否为嵌入模式
    isEmbedded() {
      return this.hideUI === true;
    }
  },
  watch: {
    // 监听homeId的变化，重新加载数据
    homeId: {
      handler(newVal) {
        if (newVal) {
          this.queryParams.homeId = newVal;
          this.getList();
        }
      },
      immediate: true
    }
  },
  mounted() {
    // 如果是嵌入模式，添加样式类
    if (this.isEmbedded) {
      this.$nextTick(() => {
        const container = this.$el.querySelector('.app-container');
        if (container) {
          container.classList.add('embedded-mode');
        }
      });
    }
  }
};
</script>

<style lang="scss">
.text-danger {
  color: #f56c6c;
  font-weight: bold;
}

.text-warning {
  color: #e6a23c;
  font-weight: bold;
}

.text-success {
  color: #67c23a;
}

/* 嵌入模式样式优化 */
.app-container {
  &.embedded-mode {
    padding: 0;
    margin: 0;

    .el-table {
      margin-bottom: 0;
    }

    .el-pagination {
      margin-top: 10px;
      justify-content: center;
    }
  }
}

/* 附件对话框样式 */
.attachment-container {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;

  .el-row {
    margin-bottom: 10px;

    .el-button {
      width: 100%;
      text-align: left;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;

      i {
        margin-right: 5px;
      }
    }
  }
}
</style>
